package com.thunisoft.netty.custom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @title NettyCustomServer.java
 * @package com.thunisoft.netty.custom
 * @projectName spring.boot
 * @author yzj 
 * @date 2019年10月8日 下午5:39:41
 */
public class NettyCustomServer {
	private int port ;
	
	public NettyCustomServer(int port) {
		this.port = port;
	}
	
	public void startUp() {
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
	    EventLoopGroup workerGroup = new NioEventLoopGroup();
	    try {
	      ServerBootstrap b = new ServerBootstrap();
	      b.option(ChannelOption.SO_BACKLOG, 1024);
	      b.group(bossGroup, workerGroup)
	          .channel(NioServerSocketChannel.class)
	          .handler(new LoggingHandler(LogLevel.INFO))
	          .childHandler(new NettyCustomServerInitializer());
	      Channel ch = b.bind(port).sync().channel();
	      System.out.printf("custom协议启动地址：127.0.0.1:%d/\n", port);
	      ch.closeFuture().sync();
	    } catch (Exception e) {
	      e.printStackTrace();

	    } finally {
	      //关闭服务
	      bossGroup.shutdownGracefully();
	      workerGroup.shutdownGracefully();
	    }
	}

	public static void main(String[] args) {
		new NettyCustomServer(8888).startUp();
	}

}
